<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2017/6/13
 * Time: 14:22
 */

namespace WeiChat\api;

use WeiChat\api\dll\Curl;

class WeixinApi extends Curl {
    protected static $instance = null;
    protected $logObj = null;
    protected $config = null;
    protected $access_token = null;
    protected $expires_in = null;//凭证有效时间，单位：秒
    protected $expires_time = null;//凭证获取时间
    public $openid = null;
    protected $access_token_user = null;
    protected $refresh_token_user = null;

    /**
     * @return WeixinApi
     */
    public static function getInstance(){
        if(!(static::$instance instanceof static)){
            static::$instance = new static();
        }
        return static::$instance;
    }

    private function __construct()
    {
        if($this->config == null){
            $this->config = new WeixinConfig();
        }
        if($this->logObj == null){
            ini_set('date.timezone','Asia/Shanghai');
            header("Content-type:text/html;charset=utf-8");
            require_once 'dll\log.php';
            $logHandler= new \CLogFileHandler(__DIR__."/logs/".date('Y-m-d').'.log');
            $this->logObj = \Log::Init($logHandler, 15);
//            \Log::DEBUG("logoTest:" . "abc");
        }
    }

    public function index(){
        echo "weixinApi";
    }

    private function getAccessToken(){
        if($this->access_token && $this->expires_time && $this->expires_time && (time() - $this->expires_time < $this->expires_in)){
            return $this->access_token;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token".
            "?grant_type=client_credential".
            "&appid=".WeixinConfig::APPID.
            "&secret=".WeixinConfig::APPSECRET;
        $res = $this->curlGet($url);
        $this->access_token = $res['access_token'];
        $this->expires_in = $res['expires_in'];
        $this->expires_time = time();
        return $this->access_token;
    }

    public function getOpenId($redirect_uri,$state = 'STATE'){
        if(!isset($_GET['code'])){
            if(!$redirect_uri){
                $redirect_uri = WeixinConfig::REDIRECT_URI;
            }
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize".
                "?appid=".WeixinConfig::APPID.
                "&redirect_uri=".urlencode($redirect_uri).
//                "&redirect_uri=".urlencode('http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].$_SERVER['QUERY_STRING']).
                "&response_type=code".
                "&scope=snsapi_userinfo".
//                "&scope=snsapi_base".
                "&state=".$state.
                "#wechat_redirect";
            header("Location: $url");exit();
        }else{
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token".
                "?appid=".WeixinConfig::APPID.
                "&secret=".WeixinConfig::APPSECRET.
                "&code=".$_GET['code'].
                "&grant_type=authorization_code";
            $res = $this->curlGet($url);
            $this->access_token_user = $res['access_token'];
            $this->refresh_token_user = $res['refresh_token'];
            $this->openid = $res['openid'];
            return $res;
        }
    }

    public function getUserInfo(){
        if(!$this->access_token_user && !$this->openid){
            echo "need openid";die;
        }
        $url = "https://api.weixin.qq.com/sns/userinfo?".
            "access_token=".$this->access_token_user.
            "&openid=".$this->openid.
            "&lang=zh_CN";
        $res = $this->curlGet($url);
        return $res;
    }

    public function unifyPay($body,$fee,$trade_no = null,$notify_url = null,$tag = '',$attach=''){
        require_once __DIR__."/lib/WxPay.Api.php";
        require_once __DIR__."/WxPay.JsApiPay.php";
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        //设置商品或支付单简要描述
        $input->SetBody($body);
        //设置附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
        $input->SetAttach($attach);
        if($trade_no){
            //设置商户系统内部的订单号，当没提供transaction_id时需要传这个。
            $input->SetOut_trade_no($trade_no);
        }else{
            $input->SetOut_trade_no(\WxPayConfig::MCHID.date("YmdHis"));
        }

        //设置订单总金额，单位为分，只能为整数，详见支付金额
        $input->SetTotal_fee($fee);
        //设置订单生成时间，格式为yyyyMMddHHmmss，如2009年12月25日9点10分10秒表示为20091225091010。详见时间规则
        $input->SetTime_start(date("YmdHis"));
        //设置订单失效时间，格式为yyyyMMddHHmmss，如2009年12月27日9点10分10秒表示为20091227091010。详见时间规则
        $input->SetTime_expire(date("YmdHis", time() + 600));
        //设置商品标记，代金券或立减优惠功能的参数，说明详见代金券或立减优惠
        $input->SetGoods_tag($tag);
        if($notify_url){
            //设置接收微信支付异步通知回调地址
            $input->SetNotify_url($notify_url);
        }else{
            $input->SetNotify_url("http://123.207.2.19:888/example/notify.php?coder="."nano");
        }

        //设置取值如下：JSAPI，NATIVE，APP，详细说明见参数规定
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($this->openid);
        $order = \WxPayApi::unifiedOrder($input);
        echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
        foreach($order as $key=>$value){
            echo "<font color='#00ff55;'>$key</font> : $value <br/>";
        }
        $tools = new \JsApiPay();
        $jsApiParameters = $tools->GetJsApiParameters($order);
        return $jsApiParameters;
    }
}

